import { throttle } from 'lodash-es'
import { ref, watch } from 'vue'

const PAGINATION_HEIGHT = 56 // px

export function useTableHeight(hasPagination = true) {
  const tableRef = ref()
  const tableHeight = ref()

  const calculateHeight = () => {
    const pureTableEl = tableRef.value.getTableDoms().tableWrapper.parentElement
    const pureTableHeight = pureTableEl.offsetHeight

    tableHeight.value = pureTableHeight - (hasPagination ? PAGINATION_HEIGHT : 0)
  }
  const throttledCalculateHeight = throttle(calculateHeight, 200)

  // 处理动态赋值 ref 的情况
  watch(
    tableRef,
    (v) => {
      if (v) calculateHeight()
    },
    { immediate: true }
  )

  onMounted(() => {
    window.addEventListener('resize', throttledCalculateHeight)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', throttledCalculateHeight)
  })

  return { tableRef, tableHeight }
}
